package util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.administrator.text.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import app.MyApplication;
import entity.HomeZhuYe;

/**
 * Created by Administrator on 2016/7/5.
 * 图片处理类
 */
public class BitmapUtil{
     private ImageLoader mImageLoader;
     private DisplayImageOptions mDisplayImageOptions;
     private OnBitmapClickListenerList mOnBitmapClickListener;
     private Set<String> mSet;
     private List<Bitmap> listBitmao = new ArrayList<>();
     private int mPosition;
     private Map<String,String> mMap;
     public static final String PHOSE ="/phose/";             //压缩图片 再保存
     private OnBitMapClickListener mOnBitMapClickListener;
     private static BitmapUtil mBitmapUtil;

     public static BitmapUtil newBitmap(){
         if(mBitmapUtil == null){
             synchronized (BitmapUtil.class){
                 if(mBitmapUtil == null){
                     mBitmapUtil = new BitmapUtil();
                 }
             }
         }
         return mBitmapUtil;
     }

    /**
     * 质量压缩方法
     *这些操作很耗时，就不循环了，如果照片大于5M，就直接压缩百分之60
     */
    public Bitmap compressImage(Bitmap image) {
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       image.compress(Bitmap.CompressFormat.JPEG, 40, baos);
       ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
       Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }

    /**保存到SD卡并且保存相册
     * @param bm
     *            图片的bitmap
     * @param fileName
     *            文件名
     * @throws IOException
     */
    public void saveJPGFile(Context context,Bitmap bm,String fileName,String albu_paha)
            throws IOException {
        File dirFile = new File(albu_paha);
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(albu_paha + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();

          String release = android.os.Build.VERSION.RELEASE;
          String tempID = release.substring(0, 3);
        if(Double.parseDouble(tempID) >= 4.4){//安卓4.4以上版本的时候使用这个，以下的使用else语句里面的

        }else {

            // 其次把文件插入到系统图库
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                        myCaptureFile.getAbsolutePath(), fileName, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
        Intent intent1 = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(dirFile);
        intent1.setData(uri);
        context.sendBroadcast(intent1);

    }

    /**
     * 将压缩的bitmap保存到SDCard卡临时文件夹，用于上传
     */
    public void saveMyBitmap(String filename, Bitmap bit) {
        String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath().toString()+File.separator;
        File dir = new File(baseDir);
        if (!dir.exists()) {
            dir.mkdir();//如果路径不存在就先创建路径
            Log.e("Options", "      创建");
        }
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File f = new File(dir,filename);
            FileOutputStream fOut = null;
            try {
                fOut = new FileOutputStream(f);
                bit.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                fOut.flush();
                fOut.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }finally {
                if(fOut !=null){
                    try {
                        fOut.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 递归删除
     */
    public void recursionDeleteFile(File file){
        if(file.isFile()){
            file.delete();//isFile()判断是否是文件，若是，返回true,执行if中的删除
            return;
        }
        if(file.isDirectory()){
            File[] childFile = file.listFiles();//idDirectory()判断是否是目录，若是，返回true,答案D取反，意思就变成了不是目录才执行if,所以也是正解
            if(childFile == null || childFile.length == 0){
                file.delete();
                return;
            }
            for(File f : childFile){
                recursionDeleteFile(f);
            }
            file.delete();
        }
    }

    /**
     * 显示图片类
     * @param context 上下文
     * @param url 传进之前的图片地址
     * @param imageView ImageView对象
     * @param icon 默认图标 0 时 DisplayImageOptions外界传入
     * DisplayImageOptions 可以自己传入对象
     */
    public void showBitmap(Context context,final String url,final ImageView imageView,final int icon,final DisplayImageOptions displayImageOptions){
        if(mImageLoader == null){
            mImageLoader = MyApplication.getApp().getImageLoader();
        }
        if(displayImageOptions == null){
            mDisplayImageOptions = HomeUtil.getHemeUtilNew().getDisplayImageOptions(true,icon);
        }else {
            mDisplayImageOptions = displayImageOptions;
        }

        if(NetUtils.getInstance(context).getNetWorkTeyt() == 0 ){
            mImageLoader.displayImage(url,imageView, mDisplayImageOptions);
        }else if(NetUtils.getInstance(context).getNetWorkTeyt() == 1){
            String server =MyApplication.getApp().getFWQString();
            int i = server.indexOf("pro");
            server = server.substring(0,i);
            int i1 = url.indexOf("wifi");
            String imUrl = url.substring(i1,url.length());
            LogUtil.eE("imUrl",server+imUrl);
            LogUtil.eE("imUrl",imageView+"");
            mImageLoader.displayImage(server+imUrl,imageView,mDisplayImageOptions);
        }
    }

    /**
     * 先判断本地集合中是否有该图片的地址
     * @param url 图片地址
     * @param imageView 图片控件
     *轮播图的 position
     */
     public void setBitmap(Context context,String url,ImageView imageView,int position){

        if(mSet == null){mSet = new HashSet<>();}
        if(mMap == null){mMap = new HashMap<>();}
        if(mImageLoader == null){mImageLoader = MyApplication.getApp().getImageLoader();}
        DisplayImageOptions displayImageOptions = HomeUtil.getHemeUtilNew().getDisplayImageOptions(true,R.mipmap.pre_home_head);
        mImageLoader.displayImage(url,imageView,displayImageOptions);
        if(mSet.contains(url)){
            String urlBitmap = mMap.get(position+"");
            LogUtil.eE("Bitmap","复用"+position);
            mImageLoader.displayImage(urlBitmap,imageView,displayImageOptions);
        }else {
            LogUtil.eE("Bitmap","进来没请求"+position);
            getBitmap(context,url,imageView,position,displayImageOptions);
        }

    }

    public void getBitmap(final Context context, final String url, final ImageView imageView, final int position, final DisplayImageOptions displayImageOptions){
        String  picUrl = "";
        if(NetUtils.getInstance(context).getNetWorkTeyt() == 0 ){
            mImageLoader.displayImage(url,imageView, displayImageOptions);
        }else if(NetUtils.getInstance(context).getNetWorkTeyt() == 1){
            String urlString =MyApplication.getApp().getFWQString();
            if(urlString.equals(Url.getUrlNew().getAppIP())){
                mImageLoader.displayImage(url,imageView,displayImageOptions);
            }else {
            picUrl = StringUtil.getStringUtilNew().getFeq(urlString,"PicServlet");
            Map<String,Object> map = new HashMap<>();
            map.put("picUrl",url);
            LogUtil.eE("picUrl",url+"");
            LogUtil.eE("picUrl",picUrl+"");
            LogUtil.eE("Bitmap","picUrl"+picUrl);
            GreenTreeNetworkUtil.getInstance().doPost(context,picUrl,1,map,new RequestDataCallback() {
                @Override public void onSuccess(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String pic = jsonObject.getString("picUrl");
                        LogUtil.eE("Bitmap","图片"+pic);
                        mSet.add(url);
                        mMap.put(""+position,pic);
                        if(!pic.equals("")){
                         mImageLoader.displayImage(pic,imageView,displayImageOptions);
                        }
                    } catch (JSONException e) {e.printStackTrace();}
                }

                @Override public void onFailure(Throwable error) {
                    LogUtil.eE("Bitmap","onFailure............."+error);
                }
            });
         }
        }
    }

    /**
     *返回首页图片
     */
    public void getListBimap(List<HomeZhuYe.BannerModelsBean.PicModelsBean> list,OnBitmapClickListenerList onBitmapClickListenerList){
        mPosition = 0;
        this.mOnBitmapClickListener = onBitmapClickListenerList;
        DisplayImageOptions displayImageOptions = HomeUtil.getHemeUtilNew().getDisplayImageOptions(true,R.mipmap.pre_home_head);
        if(mImageLoader == null){
            mImageLoader = MyApplication.getApp().getImageLoader();
        }
        getBimap(displayImageOptions,list);
    }

    private void getBimap(final DisplayImageOptions displayImageOptions, final List<HomeZhuYe.BannerModelsBean.PicModelsBean> list){
        mImageLoader.loadImage(list.get(mPosition).getPic(),displayImageOptions,new SimpleImageLoadingListener(){
            @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                super.onLoadingComplete(imageUri, view, loadedImage);
                if(loadedImage !=null){
                    mPosition ++;
                    listBitmao.add(loadedImage);
                    if(listBitmao.size() == list.size()){
                       if(mOnBitmapClickListener !=null){mOnBitmapClickListener.onBitmapClick(listBitmao);}
                    }else {
                        getBimap(displayImageOptions,list);
                    }
                }
            }
        });
    }

    /**
     * 目前是上网接口的回掉
     * 定义接口 用于itme  的回调
     */
    public interface OnBitMapClickListener {
        void onItemClick(String paty);
    }

    /**
     * 把图片数据送回去
     */
    public interface OnBitmapClickListenerList {
        void onBitmapClick(List<Bitmap> list);
    }

    public void setOnItemClickListener(OnBitMapClickListener listener) {
        this.mOnBitMapClickListener = listener;
    }
}
